﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace Ession
{
    public class HttpGetter
    {

        public HttpGetter()
        {
            cookie = new CookieContainer();
        }

        public bool completed = false;
        public CookieContainer cookie;
        public HttpWebRequest request;
        public HttpWebResponse response;
        public string url = "";
        private IAsyncResult AR;

        /// <summary>
        /// 以Get方式访问网址
        /// </summary>
        /// <param name="URL"></param>
        /// <returns></returns>
        public string GetHtml(string URL, WebProxy proxy = null, int timeOut = 8000)
        {
            try
            {

                request = HttpWebRequest.Create(URL) as HttpWebRequest;
                request.Method = "GET";
                if (proxy != null)
                {
                    WebRequest.DefaultWebProxy = proxy;
                    request.Proxy = proxy;
                }

                request.Timeout = timeOut;
                request.UseDefaultCredentials = true;

                request.CookieContainer = cookie;

                response = request.GetResponse() as HttpWebResponse;
                return new StreamReader(response.GetResponseStream()).ReadToEnd();
            }
            catch (Exception ex)
            {
                return "";
            }
        }


        public void GetHtmlAsyc(string URL, Action<string> Result, WebProxy proxy = null, int timeOut = 8000)
        {
            try
            {
                request = HttpWebRequest.Create(URL) as HttpWebRequest;
                request.Method = "GET";
                if (proxy != null)
                {
                    request.Proxy = proxy;
                    WebRequest.DefaultWebProxy = proxy;

                }
                request.UseDefaultCredentials = true;
                request.CookieContainer = cookie;
                request.Timeout = timeOut;
                AR = request.BeginGetResponse(
                    (s) =>
                    {
                        if (s.IsCompleted)
                        {
                            try
                            {
                                response = request.EndGetResponse(AR) as HttpWebResponse;
                                Result(new StreamReader(response.GetResponseStream()).ReadToEnd());
                                completed = true;
                            }
                            catch (Exception ex)
                            {
                                Result(null);
                            }

                        }
                    }, request
                    );

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
